package org.buptsse.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.AddressLocation;
import org.buptsse.entity.BookItem;
import org.buptsse.thread.GetLocationThread;
import org.buptsse.thread.UpdateUserPhotoThread;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.Base64Helper;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PostNewBookActivity extends Activity {

	
	private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
    
    private BookItem book=new BookItem();
    
    //private ImageView bookImage;
    private Button addImageButton,scanButton,publishBookButton,backButton;
    protected LocationManager locationManager;
    private EditText bookNameET,isbnET,priceET,numberET,
    				authorET,publisherET,descriptionET;
    private TextView locationTV;
    private LinearLayout photoLayout;
    private ProgressDialog pDialog;
    private TextView qualityTV;
    private String[] qualityStrings={"全新","九成新","七八成新","七成新以下"};
    private boolean getPhoto=false,getLocation=false;
    
    private Handler handler=new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;

			case APPConstant.getBookInfoError:
				Toast.makeText(getApplicationContext(), "获取图书信息失败", 1000).show();
				stopWaitting();
				break;
			case APPConstant.publishBookError:
				Toast.makeText(getApplicationContext(), "发布失败", 1000).show();
				break;
			case APPConstant.getBookInfoFinish:
				book=(BookItem) msg.obj;
				//Toast.makeText(getApplicationContext(), "bookname:"+book.getBookname()+" bookid:"+book.getBookid(), 1000).show();
				bookNameET.setText(book.getBookname());
				authorET.setText(book.getAuthor());
				publisherET.setText(book.getPublish());
				stopWaitting();
				break;
			case APPConstant.publishBookFinish:
				Toast.makeText(getApplicationContext(), "发布成功", 1000).show();
				bookNameET.setText("");
				isbnET.setText("");
				priceET.setText("0");
				numberET.setText("1");
				authorET.setText("");
				publisherET.setText("");
				qualityTV.setText(qualityStrings[0]);
				descriptionET.setText("");
				locationTV.setText("");
				for(int i=1;i<photoLayout.getChildCount();i++)
				{
					photoLayout.removeViewAt(i);
				}
				stopWaitting();
				break;
			case APPConstant.getCurrentLocationError:
				Toast.makeText(getApplicationContext(), "定位失败", 1000).show();
				locationTV.setText("定位失败(点击重新定位)");
				break;
			case APPConstant.getCurrentLocationFinish:
				AddressLocation location=(AddressLocation) msg.obj;
				book.setLongtitude(location.getLongtitude());
				book.setLatitude(location.getLatitude());
				book.setAddres(location.getAddress());
				if(location.getAddress()!=null)
				{
					locationTV.setText(location.getAddress());
				}else {
					locationTV.setText("定位成功");
				}
				break;
			case APPConstant.requireGPS:
				openGPSDialog();
				break;
			}
    		super.handleMessage(msg);
    	}
    };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去掉任务条
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.l_post_book_info);
		
		bookNameET=(EditText) findViewById(R.id.bookname);
		isbnET=(EditText) findViewById(R.id.isbn);
		priceET=(EditText) findViewById(R.id.price);
		numberET=(EditText) findViewById(R.id.number);
		authorET=(EditText) findViewById(R.id.author);
		publisherET=(EditText) findViewById(R.id.publisher);
		qualityTV=(TextView) findViewById(R.id.quality);
		descriptionET=(EditText) findViewById(R.id.description);
		qualityTV.setText(qualityStrings[0]);
		qualityTV.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShowQualityDialog();
			}
		});
		locationTV=(TextView) findViewById(R.id.location);
		locationTV.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				GetLocationThread glt=new GetLocationThread(PostNewBookActivity.this, handler,true);
				glt.start();
				locationTV.setText("正在定位...");
			}
		});
		photoLayout=(LinearLayout) findViewById(R.id.photos_layout);
		
		//图书照片
        //bookImage=(ImageView) findViewById(R.id.book_image);
        //添加照片
        addImageButton=(Button) findViewById(R.id.add_image);
        addImageButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ChooseImage();
				//showCurrentLocation();
			}
		});
        //扫描按钮
        scanButton=(Button) findViewById(R.id.scan_button);
        scanButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//Toast.makeText(getApplicationContext(), "start activity", 1000).show();
				Intent intent=new Intent();
				intent.setClass(PostNewBookActivity.this, CaptureActivity.class);
				startActivityForResult(intent, GET_ISBN);
			}
		});
        //发布按钮
        publishBookButton=(Button) findViewById(R.id.publish_book_button);
        publishBookButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loading("正在发布...");
				PublishBook();
			}
		});
        //返回按钮
        backButton=(Button) findViewById(R.id.bt_back);
        backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
	}
	
	private void ShowQualityDialog() {
		new AlertDialog.Builder(this).setTitle("成色")
				.setItems(qualityStrings, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						qualityTV.setText(qualityStrings[which]);
					}
				}).show();
	}
	
	private void openGPSDialog() {
		  AlertDialog.Builder builder = new Builder(PostNewBookActivity.this);
		  builder.setMessage("GPS未打开，现在打开吗？");
		  builder.setTitle("提示");
		  builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
		   @Override
		   public void onClick(DialogInterface dialog, int which) {
			   Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
	           startActivityForResult(intent,0); //此为设置完成后返回到获取界面
	           GetLocationThread glt=new GetLocationThread(PostNewBookActivity.this, handler, true);
	           glt.start();
		   }
		  });
		  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
		   @Override
		   public void onClick(DialogInterface dialog, int which) {
			   GetLocationThread glt=new GetLocationThread(PostNewBookActivity.this, handler, false);
	           glt.start();
			   dialog.dismiss();
		   }
		  });
		  builder.create().show();
		 }
	
	
	public void loading(String msg){
		pDialog = new ProgressDialog(this); 
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
    }
	
	public void stopWaitting()
	{
		pDialog.dismiss();
	}
	
	private void PublishBook()
	{
		String bookName=bookNameET.getText().toString();
		if(bookName.equals(""))
		{
			Toast.makeText(getApplicationContext(), "请输入书名", 1000).show();
			return;
		}
		book.setBookname(bookName);
		String isbn=isbnET.getText().toString();
		if(isbn.equals(""))
		{
			Toast.makeText(getApplicationContext(), "请输入ISBN号", 1000).show();
			return;
		}
		book.setIsbn(isbn);
		String price=priceET.getText().toString();
		if(price.equals(""))
		{
			Toast.makeText(getApplicationContext(), "请输入价格", 1000).show();
			return;
		}
		book.setPrice(price);
		String number=numberET.getText().toString();
		if(number.equals(""))
		{
			Toast.makeText(getApplicationContext(), "请输入数量", 1000).show();
			return;
		}
		book.setNumber(number);
		String author=authorET.getText().toString();
		book.setAuthor(author);
		String publiser=publisherET.getText().toString();
		book.setPublish(publiser);
		String comment=descriptionET.getText().toString();
		book.setComment(comment);
		book.setSeller(GloableInstance.user.getName());
		book.setCondition(qualityTV.getText().toString());
		
		PublishBookThread pt=new PublishBookThread(getApplicationContext(), book);
		pt.start();
	}

	private class PublishBookThread extends Thread
	{
		private Context context;
		private BookItem bookItem;
		
		public PublishBookThread(Context context,BookItem bookItem)
		{
			this.context=context;
			this.bookItem=bookItem;		
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			//System.out.println("longtitude:"+bookItem.getLongtitude());
			//System.out.println("latitude:"+bookItem.getLatitude());
			//System.out.println("address:"+bookItem.getAddres());
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			if(bookItem.getBookid()!=null && !bookItem.getBookid().equals(""))
				param.add(new BasicNameValuePair("bookid", bookItem.getBookid()));
			if(bookItem.getLatitude()!=null && !bookItem.getLatitude().equals(""))
				param.add(new BasicNameValuePair("latitude", bookItem.getLatitude()));
			if(bookItem.getLongtitude()!=null && !bookItem.getLongtitude().equals(""))
				param.add(new BasicNameValuePair("longtitude", bookItem.getLongtitude()));
			if(bookItem.getAddres()!=null && !bookItem.getAddres().equals(""))
			{
				param.add(new BasicNameValuePair("address", bookItem.getAddres()));
			}
			param.add(new BasicNameValuePair("seller", bookItem.getSeller()));
			param.add(new BasicNameValuePair("price", bookItem.getPrice()));
			param.add(new BasicNameValuePair("condition", bookItem.getCondition()));
			param.add(new BasicNameValuePair("comment", bookItem.getComment()));
			param.add(new BasicNameValuePair("isbn", bookItem.getIsbn()));
			param.add(new BasicNameValuePair("publisher", bookItem.getPublish()));
			param.add(new BasicNameValuePair("author", bookItem.getAuthor()));
			param.add(new BasicNameValuePair("booknumber",""+bookItem.getPhotoCount()));
			if(bookItem.getPhotoList().size()>0)
			{
				param.add(new BasicNameValuePair("pictureNumber", ""+bookItem.getPhotoCount()));
				
				for(int j=0;j<bookItem.getPhotoCount();j++)
				{
					Bitmap bitmap=bookItem.getPhotoList().get(j);
					ByteArrayOutputStream os=new ByteArrayOutputStream();
					bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
					byte[] data=os.toByteArray();
					String pic_data=Base64Helper.encode(data, 0, data.length);
					param.add(new BasicNameValuePair("picture"+j, pic_data));
				}
			}
			try {
				String result=HttpHelper.sendPost(APPConstant.publishBookUrl, param);
				//System.out.println("publish book result:"+result);
				if(result.contains("success"))
				{
					Message msg=handler.obtainMessage(APPConstant.publishBookFinish);
					handler.sendMessage(msg);
					return;
				}else {
					Message msg=handler.obtainMessage(APPConstant.publishBookFinish);
					handler.sendMessage(msg);
					return;
				}
			} catch (ClientProtocolException e) {
				Message msg=handler.obtainMessage(APPConstant.publishBookError);
				handler.sendMessage(msg);
				return;
			} catch (IOException e) {
				Message msg=handler.obtainMessage(APPConstant.publishBookError);
				handler.sendMessage(msg);
				return;
			}
		}
	}
	
	private class GetBookInfoThread extends Thread
	{
		private String isbn;
		private Context context;
		
		public GetBookInfoThread(Context context,String isbn)
		{
			this.context=context;
			this.isbn=isbn;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("username", GloableInstance.user.getName()));
			param.add(new BasicNameValuePair("isbn", this.isbn));
			try {
				String json=HttpHelper.sendPost(APPConstant.getBookInfoByISBNUrl, param);
				//System.out.println("get book info ,json:"+json);
				//System.out.println("last is:"+json.charAt(json.length()-1));
				//System.out.println("last is:"+json.charAt(json.length()-2));
				//System.out.println("last is:"+json.charAt(json.length()-3));
				if(!json.equals("failure"))
				{
					List<BookItem> list=(LinkedList<BookItem>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<BookItem>>() {}.getType());
					if(list!=null && list.size()>0)
					{
						Message msg=handler.obtainMessage(APPConstant.getBookInfoFinish);
						msg.obj=list.get(0);
						handler.sendMessage(msg);
						return;
					}else {
						Message msg=handler.obtainMessage(APPConstant.getBookInfoError);
						handler.sendMessage(msg);
					}
				}else {
					Message msg=handler.obtainMessage(APPConstant.getBookInfoError);
					handler.sendMessage(msg);
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				Message msg=handler.obtainMessage(APPConstant.getBookInfoError);
				handler.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				Message msg=handler.obtainMessage(APPConstant.getBookInfoError);
				handler.sendMessage(msg);
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				Message msg=handler.obtainMessage(APPConstant.getBookInfoError);
				handler.sendMessage(msg);
			}
		}
	}
	
	String[] type={"拍照","从文件中选择"};
	final int TAKE_PHOTO_WITH_DATA=1;
	final int TAKE_PHOTO_FROM_FILE=2; 
	final int PHOTO_CROP_FINISH=3;
	final int GET_ISBN=4;
	
	public void ChooseImage()
	{
		new AlertDialog.Builder(this).setTitle("选择照片")
		.setItems(type, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				switch (which) {
				case 0:
					//拍照
					Intent intent = new Intent(  
                            MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri  
                            .fromFile(new File(Environment  
                                    .getExternalStorageDirectory(),  
                                    "cloudLearning_temp.jpg")));
					startActivityForResult(intent, TAKE_PHOTO_WITH_DATA);
					break;

				case 1:
					//从文件选择
					Intent intent2 = new Intent(Intent.ACTION_PICK, null);  
	                /* 开启Pictures画面Type设定为image */    
					intent2.setDataAndType(  
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  
                            "image/*");  
	                startActivityForResult(intent2, TAKE_PHOTO_FROM_FILE);
					break;
				}
			}
		}).create().show();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		if(resultCode!=RESULT_OK)
            return;
		switch (requestCode) {
		case TAKE_PHOTO_WITH_DATA:
			File temp = new File(Environment.getExternalStorageDirectory()  
                    + "/cloudLearning_temp.jpg");  
            startPhotoZoom(Uri.fromFile(temp));
			break;
		case TAKE_PHOTO_FROM_FILE:
			startPhotoZoom(data.getData());
			break;
		case PHOTO_CROP_FINISH:
			Bitmap photoCroped = (Bitmap) data.getExtras().get("data");
			if(photoCroped!=null){
				book.addBitmap(photoCroped);
				ImageView imageView=new ImageView(getApplicationContext());
				imageView.setImageBitmap(photoCroped);
				imageView.setOnLongClickListener(new OnLongClickListener() {
					
					@Override
					public boolean onLongClick(final View v) {
						AlertDialog.Builder builder = new Builder(PostNewBookActivity.this);
						  builder.setMessage("确定删除吗？");
						  builder.setTitle("提示");
						  builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						   @Override
						   public void onClick(DialogInterface dialog, int which) {
							   int index=1;
							   while(v!=photoLayout.getChildAt(index))
								   index++;
							   book.deleteBitmap(index-1);
							   photoLayout.removeViewAt(index);
						   }
						  });
						  builder.setNegativeButton("取消", null);
						  builder.create().show();
						return false;
					}
				});
				photoLayout.addView(imageView);
				getPhoto=true;
			}
			break;
		case GET_ISBN:
			//成功获取图书ISBN号码
			String isbn=data.getStringExtra("isbn");
			isbnET.setText(isbn);
			GetBookInfoThread gt=new GetBookInfoThread(this, isbn);
			gt.start();
			loading("正在获取图书信息");
			//Toast.makeText(getApplicationContext(), "isbn:"+isbn, 1000).show();
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	public void startPhotoZoom(Uri uri) {  
        /*  
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页  
         * yourself_sdk_path/docs/reference/android/content/Intent.html  
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,  
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么  
         * 制做的了...吼吼  
         */ 
        Intent intent = new Intent("com.android.camera.action.CROP");  
        intent.setDataAndType(uri, "image/*");  
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪  
        intent.putExtra("crop", "true");  
        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);  
        intent.putExtra("aspectY", 1);  
        // outputX outputY 是裁剪图片宽高  
        intent.putExtra("outputX", 150);  
        intent.putExtra("outputY", 150);  
        intent.putExtra("return-data", true);  
        startActivityForResult(intent, PHOTO_CROP_FINISH);  
    } 
	
}